<template>
  <div class="booking-container">
    <el-card class="booking-card">
      <template #header>
        <div class="card-header">
          <span class="title">预约时间段查询</span>
          <div class="header-right">
            <el-select
              v-model="selectedStoreId"
              placeholder="请选择店铺"
              class="store-select"
              @change="handleStoreChange"
            >
              <el-option
                v-for="store in storeList"
                :key="store.id"
                :label="store.name"
                :value="store.id"
              />
            </el-select>
            <el-button
              type="primary"
              plain
              size="small"
              class="settings-btn"
              @click="showSettingsDialog"
            >
              <el-icon><Setting /></el-icon> 设置
            </el-button>
            <el-button type="success" plain size="small" @click="exportToExcel">
              <el-icon><Download /></el-icon> 导出Excel
            </el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="booking-content">
        <!-- 门店营业时间信息 -->
        <div v-if="currentStore" class="store-business-hours">
          <el-alert type="info" :closable="false">
            <div class="store-info">
              <div>
                <el-icon><Shop /></el-icon>
                <strong>{{ currentStore.name }}</strong>
              </div>
              <div>
                <el-icon><Clock /></el-icon> 营业时间:
                {{ currentStore.businessHours || "9:00-21:00" }}
              </div>
            </div>
          </el-alert>
        </div>

        <!-- 日期选择器 -->
        <div class="date-selector">
          <el-radio-group
            v-model="selectedDateIndex"
            size="large"
            @change="handleDateChange"
          >
            <el-radio-button
              v-for="(dateItem, index) in dateList"
              :key="index"
              :label="index"
              :class="{ 'is-today': dateItem.isToday }"
            >
              <div class="date-item">
                <div class="week-day">{{ dateItem.weekDay }}</div>
                <div class="date">{{ dateItem.displayDate }}</div>
              </div>
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 图例说明 -->
        <div class="legend">
          <div class="legend-item">
            <span class="color-dot available" />
            <span>可预约 (人数＜{{ thresholds.available }})</span>
          </div>
          <div class="legend-item">
            <span class="color-dot busy" />
            <span
              >较忙 ({{ thresholds.available }}-{{ thresholds.busy }}人)</span
            >
          </div>
          <div class="legend-item">
            <span class="color-dot full" />
            <span>拥挤 (＞{{ thresholds.busy }}人)</span>
          </div>
        </div>

        <!-- 预约时间段网格视图 -->
        <div class="time-slots-grid">
          <el-row :gutter="16">
            <el-col
              v-for="(slot, index) in timeSlotsList"
              :key="index"
              :span="6"
            >
              <el-card
                :class="['time-slot-card', getStatusClass(slot.status)]"
                shadow="hover"
              >
                <div class="time-slot-header">
                  <h3 class="time">{{ slot.time }}</h3>
                  <el-tag
                    size="small"
                    :type="getStatusType(slot.status)"
                    effect="dark"
                  >
                    {{ getStatusText(slot.status) }}
                  </el-tag>
                </div>

                <div class="time-slot-content">
                  <div class="count-info">
                    <el-progress
                      type="dashboard"
                      :percentage="getPercentage(slot.peopleCount)"
                      :color="getProgressColor(slot.status)"
                      :stroke-width="6"
                      :width="60"
                    >
                      <template #default>
                        <div class="progress-content">
                          <span class="value">{{ slot.peopleCount }}</span>
                          <span class="label">预约</span>
                        </div>
                      </template>
                    </el-progress>
                  </div>

                  <div class="staff-info">
                    <div class="staff-section">
                      <div class="staff-title">摄影师:</div>
                      <div class="staff-list">
                        <div
                          v-for="photographer in slot.photographers"
                          :key="photographer.id"
                          class="staff-item"
                        >
                          <el-avatar
                            :src="photographer.avatar"
                            :size="28"
                            class="staff-avatar"
                            :style="{
                              backgroundColor: photographer.color || '#409EFF'
                            }"
                          >
                            {{ photographer.name.substring(0, 1) }}
                          </el-avatar>
                          <span class="staff-name-tag">{{
                            photographer.name
                          }}</span>
                        </div>
                        <el-tooltip
                          v-if="slot.photographers.length === 0"
                          content="暂无安排"
                          placement="top"
                        >
                          <el-icon class="no-staff"><WarningFilled /></el-icon>
                        </el-tooltip>
                      </div>
                    </div>
                    <div class="staff-section">
                      <div class="staff-title">化妆师:</div>
                      <div class="staff-list">
                        <div
                          v-for="makeup in slot.makeupArtists"
                          :key="makeup.id"
                          class="staff-item"
                        >
                          <el-avatar
                            :src="makeup.avatar"
                            :size="28"
                            class="staff-avatar"
                            :style="{
                              backgroundColor: makeup.color || '#67C23A'
                            }"
                          >
                            {{ makeup.name.substring(0, 1) }}
                          </el-avatar>
                          <span class="staff-name-tag">{{ makeup.name }}</span>
                        </div>
                        <el-tooltip
                          v-if="slot.makeupArtists.length === 0"
                          content="暂无安排"
                          placement="top"
                        >
                          <el-icon class="no-staff"><WarningFilled /></el-icon>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="time-slot-footer">
                  <el-button
                    type="primary"
                    size="small"
                    :icon="View"
                    @click="viewTimeSlotDetail(slot)"
                  >
                    查看详情
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>

    <!-- 时间段详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentTimeSlot?.time || ''} 预约详情`"
      width="600px"
      destroy-on-close
    >
      <div v-if="currentTimeSlot" class="time-slot-detail">
        <div class="detail-section">
          <h3 class="section-title">
            <el-icon><Calendar /></el-icon>
            基本信息
          </h3>
          <div class="info-row">
            <span class="label">日期：</span>
            <span class="value">{{ formatDate(selectedDate) }}</span>
          </div>
          <div class="info-row">
            <span class="label">时间段：</span>
            <span class="value">{{ currentTimeSlot.time }}</span>
          </div>
          <div class="info-row">
            <span class="label">预约状态：</span>
            <span class="value">
              <el-tag
                :type="getStatusType(currentTimeSlot.status)"
                effect="light"
              >
                {{ getStatusText(currentTimeSlot.status) }}
              </el-tag>
            </span>
          </div>
          <div class="info-row">
            <span class="label">预约人数：</span>
            <span class="value">{{ currentTimeSlot.peopleCount }}人</span>
          </div>
        </div>

        <div class="detail-section">
          <h3 class="section-title">
            <el-icon><UserFilled /></el-icon>
            摄影师安排
          </h3>
          <el-empty
            v-if="currentTimeSlot.photographers.length === 0"
            description="暂无摄影师安排"
          />
          <div v-else class="staff-cards">
            <div
              v-for="photographer in currentTimeSlot.photographers"
              :key="photographer.id"
              class="staff-card"
            >
              <el-avatar
                :src="photographer.avatar"
                :size="50"
                :style="{ backgroundColor: photographer.color || '#409EFF' }"
              >
                {{ photographer.name.substring(0, 1) }}
              </el-avatar>
              <div class="staff-info">
                <div class="staff-name">{{ photographer.name }}</div>
                <div class="staff-tag">
                  <el-tag size="small" effect="plain" type="primary">{{
                    photographer.level
                  }}</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h3 class="section-title">
            <el-icon><MagicStick /></el-icon>
            化妆师安排
          </h3>
          <el-empty
            v-if="currentTimeSlot.makeupArtists.length === 0"
            description="暂无化妆师安排"
          />
          <div v-else class="staff-cards">
            <div
              v-for="makeup in currentTimeSlot.makeupArtists"
              :key="makeup.id"
              class="staff-card"
            >
              <el-avatar
                :src="makeup.avatar"
                :size="50"
                :style="{ backgroundColor: makeup.color || '#67C23A' }"
              >
                {{ makeup.name.substring(0, 1) }}
              </el-avatar>
              <div class="staff-info">
                <div class="staff-name">{{ makeup.name }}</div>
                <div class="staff-tag">
                  <el-tag size="small" effect="plain" type="success">{{
                    makeup.level
                  }}</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 预约客户信息列表 -->
        <div
          v-if="
            currentTimeSlot.bookingDetails &&
            currentTimeSlot.bookingDetails.length > 0
          "
          class="detail-section"
        >
          <h3 class="section-title">
            <el-icon><List /></el-icon>
            预约客户
          </h3>
          <el-table
            :data="currentTimeSlot.bookingDetails"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column prop="id" label="编号" width="80" />
            <el-table-column prop="name" label="客户姓名" width="100" />
            <el-table-column prop="phone" label="联系电话" width="120" />
            <el-table-column label="预约服务" width="180">
              <template #default="{ row }">
                <div>
                  <div>{{ row.serviceType }}</div>
                  <div class="service-duration">
                    时长: {{ row.serviceDuration }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="摄影师" align="center" width="100">
              <template #default="{ row }">
                <el-tag
                  v-if="row.photographer"
                  type="primary"
                  effect="plain"
                  size="small"
                >
                  {{ row.photographer.name }}
                </el-tag>
                <span v-else>未分配</span>
              </template>
            </el-table-column>
            <el-table-column label="化妆师" align="center" width="100">
              <template #default="{ row }">
                <el-tag
                  v-if="row.makeupArtist"
                  type="success"
                  effect="plain"
                  size="small"
                >
                  {{ row.makeupArtist.name }}
                </el-tag>
                <span v-else>未分配</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="appointmentTime"
              label="预约时间"
              width="150"
            />
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 阈值设置对话框 -->
    <el-dialog
      v-model="settingsDialogVisible"
      title="预约设置"
      width="500px"
      destroy-on-close
    >
      <div class="settings-dialog">
        <div class="settings-section">
          <h3 class="section-title">
            <el-icon><Warning /></el-icon>
            预约阈值设置
          </h3>
          <div class="settings-form">
            <el-form :model="thresholds" label-width="140px">
              <el-form-item label="可预约上限人数:">
                <el-input-number
                  v-model="thresholds.available"
                  :min="1"
                  :max="thresholds.busy"
                  :step="1"
                  size="small"
                />
                <span class="threshold-hint">低于此值为"可预约"状态</span>
              </el-form-item>
              <el-form-item label="较忙上限人数:">
                <el-input-number
                  v-model="thresholds.busy"
                  :min="thresholds.available + 1"
                  :max="20"
                  :step="1"
                  size="small"
                />
                <span class="threshold-hint">高于此值为"拥挤"状态</span>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div class="settings-section">
          <h3 class="section-title">
            <el-icon><Clock /></el-icon>
            营业时间设置
          </h3>
          <div class="settings-form">
            <el-form :model="currentStore" label-width="140px">
              <el-form-item label="门店:">
                <span>{{ currentStore?.name || "未选择门店" }}</span>
              </el-form-item>
              <el-form-item label="营业时间:">
                <el-time-picker
                  v-model="businessHoursStart"
                  format="HH:mm"
                  placeholder="开始时间"
                  size="small"
                  @change="updateBusinessHours"
                />
                <span class="time-separator">至</span>
                <el-time-picker
                  v-model="businessHoursEnd"
                  format="HH:mm"
                  placeholder="结束时间"
                  size="small"
                  @change="updateBusinessHours"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settingsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSettings"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { formatDate } from "@/utils/date";
import { getAllStores } from "@/api/costumes";
import { getBookingTimeSlotsDetail } from "@/api/bookings";
import { ElMessage } from "element-plus";
import {
  Calendar,
  UserFilled,
  MagicStick,
  WarningFilled,
  List,
  View,
  Setting,
  Shop,
  Clock,
  Warning,
  Download
} from "@element-plus/icons-vue";
import mockStores from "@/mock/stores.json";
import mockStaff from "@/mock/staff.json";
import * as XLSX from "xlsx";

// 状态定义
const loading = ref(false);
const storeList = ref<any[]>([]);
const selectedStoreId = ref("");
const dateList = ref<any[]>([]);
const selectedDateIndex = ref(0);
const currentStore = ref<any>(null);
const settingsDialogVisible = ref(false);
const businessHoursStart = ref<Date | null>(null);
const businessHoursEnd = ref<Date | null>(null);

// 阈值设置
const thresholds = reactive({
  available: 3, // 可预约状态的上限值
  busy: 5 // 较忙状态的上限值
});

const selectedDate = computed(() => {
  if (dateList.value.length > 0 && selectedDateIndex.value >= 0) {
    return dateList.value[selectedDateIndex.value].date;
  }
  return "";
});
const timeSlotsList = ref<any[]>([]);
const detailDialogVisible = ref(false);
const currentTimeSlot = ref<any>(null);

// 生成未来7天的日期
const generateDateList = () => {
  const dates = [];
  const today = new Date();
  const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

  for (let i = 0; i < 7; i++) {
    const date = new Date();
    date.setDate(today.getDate() + i);
    const dateStr = date.toISOString().split("T")[0]; // YYYY-MM-DD
    const weekDay = weekDays[date.getDay()];
    const displayDate = `${date.getMonth() + 1}-${date.getDate()}`;

    dates.push({
      date: dateStr,
      weekDay,
      displayDate,
      isToday: i === 0
    });
  }

  dateList.value = dates;
};

// 获取所有店铺
const fetchStores = async () => {
  try {
    const res = await getAllStores();
    if (res.code === 200 && res.data) {
      storeList.value = res.data;
      if (storeList.value.length > 0) {
        selectedStoreId.value = storeList.value[0].id;
        updateCurrentStore();
        fetchTimeSlots();
      }
    }
  } catch (error) {
    console.error("获取店铺列表失败:", error);
    ElMessage.error("获取店铺列表失败");
  }
};

// 更新当前选中的店铺
const updateCurrentStore = () => {
  currentStore.value = storeList.value.find(
    store => store.id === selectedStoreId.value
  );

  if (currentStore.value && currentStore.value.businessHours) {
    // 解析营业时间字符串，例如 "9:00-21:00"
    const [start, end] = currentStore.value.businessHours.split("-");
    if (start && end) {
      const [startHour, startMinute] = start.split(":").map(Number);
      const [endHour, endMinute] = end.split(":").map(Number);

      const today = new Date();
      businessHoursStart.value = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        startHour || 9,
        startMinute || 0
      );

      businessHoursEnd.value = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        endHour || 21,
        endMinute || 0
      );
    } else {
      setDefaultBusinessHours();
    }
  } else {
    setDefaultBusinessHours();
  }
};

// 设置默认营业时间
const setDefaultBusinessHours = () => {
  const today = new Date();
  businessHoursStart.value = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate(),
    9,
    0
  );
  businessHoursEnd.value = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate(),
    21,
    0
  );

  if (currentStore.value) {
    currentStore.value.businessHours = "9:00-21:00";
  }
};

// 更新营业时间
const updateBusinessHours = () => {
  if (!businessHoursStart.value || !businessHoursEnd.value) return;

  const formatTime = (date: Date) => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${hours}:${minutes}`;
  };

  const start = formatTime(businessHoursStart.value);
  const end = formatTime(businessHoursEnd.value);

  if (currentStore.value) {
    currentStore.value.businessHours = `${start}-${end}`;
  }
};

// 显示设置对话框
const showSettingsDialog = () => {
  if (!currentStore.value) {
    ElMessage.warning("请先选择门店");
    return;
  }
  settingsDialogVisible.value = true;
};

// 保存设置
const saveSettings = () => {
  // 更新显示和数据
  updateBusinessHours();

  // 重新生成数据以应用新的阈值设置
  if (process.env.NODE_ENV === "development") {
    generateMockDataForCurrentDate();
  } else {
    fetchTimeSlots();
  }

  settingsDialogVisible.value = false;
  ElMessage.success("设置已保存");
};

// 获取预约时间段详情
const fetchTimeSlots = async () => {
  if (!selectedStoreId.value || !selectedDate.value) return;

  loading.value = true;
  try {
    const res = await getBookingTimeSlotsDetail(
      selectedStoreId.value,
      selectedDate.value
    );
    if (res.code === 200 && res.data) {
      // 处理返回的数据
      timeSlotsList.value = formatTimeSlots(res.data);
    } else {
      timeSlotsList.value = [];
      ElMessage.warning("未获取到预约时间段数据");
    }
  } catch (error) {
    console.error("获取预约时间段失败:", error);
    ElMessage.error("获取预约时间段失败");
    timeSlotsList.value = [];
  } finally {
    loading.value = false;
  }
};

// 格式化时间段数据 - 在真实接口返回数据前，这里使用模拟数据
const formatTimeSlots = (data: any) => {
  // 如果后端已经返回了格式化好的数据，可以直接使用
  if (Array.isArray(data)) return data;

  // 否则，将对象格式转换为数组格式
  const result = [];
  for (const time in data) {
    if (Object.prototype.hasOwnProperty.call(data, time)) {
      const slot = data[time];

      // 根据人数和阈值设置状态
      let status = 1; // 默认可预约
      if (
        slot.number >= thresholds.available &&
        slot.number <= thresholds.busy
      ) {
        status = 2; // 较忙
      } else if (slot.number > thresholds.busy) {
        status = 3; // 拥挤
      }

      result.push({
        time,
        status,
        peopleCount: slot.number || 0,
        photographers: slot.photographers || [],
        makeupArtists: slot.makeupArtists || []
      });
    }
  }

  return result;
};

// 处理店铺变更
const handleStoreChange = () => {
  updateCurrentStore();

  if (process.env.NODE_ENV === "development") {
    // 在开发环境中，重新生成模拟数据
    generateMockDataForCurrentDate();
  } else {
    // 在生产环境中，调用真实API
    fetchTimeSlots();
  }
};

// 处理日期变更
const handleDateChange = () => {
  if (process.env.NODE_ENV === "development") {
    // 在开发环境中，生成模拟数据
    generateMockDataForCurrentDate();
  } else {
    // 在生产环境中，调用真实API
    fetchTimeSlots();
  }
};

// 为当前选中日期生成模拟数据
const generateMockDataForCurrentDate = () => {
  loading.value = true;

  try {
    // 基于日期生成一个稳定的随机种子，使同一天的数据保持一致
    const dateStr = selectedDate.value;
    const dateSeed = dateStr
      .split("-")
      .reduce((acc, num) => acc + parseInt(num), 0);

    // 使用JSON中的摄影师和化妆师数据
    const photographers = mockStaff.photographers;
    const makeupArtists = mockStaff.makeupArtists;

    // 使用当前设置的营业时间生成数据
    const generateTimeSlots = () => {
      if (!businessHoursStart.value || !businessHoursEnd.value) {
        return [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
      }

      const startHour = businessHoursStart.value.getHours();
      const endHour = businessHoursEnd.value.getHours();

      const hours = [];
      for (let hour = startHour; hour <= endHour; hour++) {
        hours.push(hour);
      }

      return hours;
    };

    const hours = generateTimeSlots();
    const timeSlots = [];

    // 生成时间段数据
    for (const hour of hours) {
      const time = `${hour}:00`;

      // 使用日期种子生成随机预约人数(0-10)
      const randomSeed = (hour * dateSeed) % 11;
      const peopleCount = Math.floor(randomSeed);

      // 根据人数和阈值设置状态
      let status = 1; // 默认可预约
      if (
        peopleCount >= thresholds.available &&
        peopleCount <= thresholds.busy
      ) {
        status = 2; // 较忙
      } else if (peopleCount > thresholds.busy) {
        status = 3; // 拥挤
      }

      // 随机分配摄影师和化妆师
      const selectedPhotographers = [];
      const selectedMakeupArtists = [];

      // 根据人数和时间段决定工作人员数量
      const photographerCount = Math.min(
        Math.ceil(peopleCount / 3),
        photographers.length
      );
      const makeupArtistCount = Math.min(
        Math.ceil(peopleCount / 3),
        makeupArtists.length
      );

      // 使用日期种子选择摄影师
      for (let i = 0; i < photographerCount; i++) {
        const index = (dateSeed + hour + i) % photographers.length;
        selectedPhotographers.push(photographers[index]);
      }

      // 使用日期种子选择化妆师
      for (let i = 0; i < makeupArtistCount; i++) {
        const index = (dateSeed + hour + i + 3) % makeupArtists.length;
        selectedMakeupArtists.push(makeupArtists[index]);
      }

      // 避免空班 - 保证至少有一名工作人员
      if (
        peopleCount > 0 &&
        selectedPhotographers.length === 0 &&
        selectedMakeupArtists.length === 0
      ) {
        const index = dateSeed % photographers.length;
        selectedPhotographers.push(photographers[index]);
      }

      timeSlots.push({
        time,
        status,
        peopleCount,
        photographers: selectedPhotographers,
        makeupArtists: selectedMakeupArtists
      });
    }

    timeSlotsList.value = timeSlots;
  } catch (error) {
    console.error("生成模拟数据失败:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 查看时间段详情
const viewTimeSlotDetail = (row: any) => {
  currentTimeSlot.value = row;

  // 如果是开发环境，给详情对话框添加更多富有信息的内容
  if (process.env.NODE_ENV === "development" && currentTimeSlot.value) {
    // 如果没有预约详情，生成模拟数据
    if (
      !currentTimeSlot.value.bookingDetails ||
      currentTimeSlot.value.bookingDetails.length === 0
    ) {
      // 随机添加预约详情
      currentTimeSlot.value.bookingDetails = [];

      // 定义服务类型
      const serviceTypes = [
        { type: "明制云肩", duration: "120分钟" },
        { type: "齐腰襦裙", duration: "90分钟" },
        { type: "宋制褙子", duration: "60分钟" },
        { type: "宋制褙子", duration: "90分钟" },
        { type: "宋制褙子", duration: "30分钟" }
      ];

      // 根据人数添加预约记录
      for (let i = 0; i < currentTimeSlot.value.peopleCount; i++) {
        const serviceIndex = Math.floor(Math.random() * serviceTypes.length);
        const service = serviceTypes[serviceIndex];

        const customer = {
          id: `C${10000 + i}`,
          name: `客户${i + 1}`,
          phone: `1381234${i.toString().padStart(4, "0")}`,
          serviceType: service.type,
          serviceDuration: service.duration,
          appointmentTime:
            formatDate(selectedDate.value) + " " + currentTimeSlot.value.time,
          // 分配摄影师和化妆师
          photographer:
            i < currentTimeSlot.value.photographers.length
              ? currentTimeSlot.value.photographers[
                  i % currentTimeSlot.value.photographers.length
                ]
              : null,
          makeupArtist:
            i < currentTimeSlot.value.makeupArtists.length
              ? currentTimeSlot.value.makeupArtists[
                  i % currentTimeSlot.value.makeupArtists.length
                ]
              : null
        };

        currentTimeSlot.value.bookingDetails.push(customer);
      }
    }
  }

  detailDialogVisible.value = true;
};

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return "success";
    case 2:
      return "warning";
    case 3:
      return "danger";
    default:
      return "info";
  }
};

// 获取状态类名
const getStatusClass = (status: number) => {
  switch (status) {
    case 1:
      return "status-available";
    case 2:
      return "status-busy";
    case 3:
      return "status-full";
    default:
      return "";
  }
};

// 获取进度条颜色
const getProgressColor = (status: number) => {
  switch (status) {
    case 1:
      return "#67C23A"; // 绿色
    case 2:
      return "#E6A23C"; // 橙色
    case 3:
      return "#F56C6C"; // 红色
    default:
      return "#909399"; // 灰色
  }
};

// 获取百分比 - 将人数转换为百分比显示
const getPercentage = (count: number) => {
  // 假设最大容量为10人
  const maxCapacity = 10;
  const percentage = Math.min(Math.round((count / maxCapacity) * 100), 100);
  return percentage;
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return "可预约";
    case 2:
      return "较忙";
    case 3:
      return "拥挤";
    default:
      return "未知";
  }
};

// 导出Excel
const exportToExcel = () => {
  if (!selectedDate.value) {
    ElMessage.warning("请先选择日期");
    return;
  }

  try {
    // 在导出前为所有时间段生成订单信息
    generateBookingDetailsForAllTimeSlots();

    // 创建工作簿
    const workbook = XLSX.utils.book_new();

    // 准备数据
    const excelData = prepareExcelData();

    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(excelData);

    // 设置列宽
    const columnWidths = [
      { wch: 8 }, // 时间段
      { wch: 10 }, // 预约状态
      { wch: 10 }, // 预约人数
      { wch: 25 }, // 摄影师
      { wch: 25 }, // 化妆师
      { wch: 40 } // 订单信息
    ];
    worksheet["!cols"] = columnWidths;

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(
      workbook,
      worksheet,
      `预约数据-${formatDate(selectedDate.value)}`
    );

    // 获取当前店铺名称
    const storeName = currentStore.value ? currentStore.value.name : "未知店铺";

    // 导出文件名
    const fileName = `${storeName}-预约数据-${formatDate(selectedDate.value)}.xlsx`;

    // 导出Excel
    XLSX.writeFile(workbook, fileName);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出Excel失败:", error);
    ElMessage.error("导出Excel失败");
  }
};

// 为所有时间段生成订单信息
const generateBookingDetailsForAllTimeSlots = () => {
  // 定义服务类型
  const serviceTypes = [
    { type: "明制云肩", duration: "120分钟" },
    { type: "齐腰襦裙", duration: "90分钟" },
    { type: "宋制褙子", duration: "60分钟" },
    { type: "宋制褙子", duration: "90分钟" },
    { type: "汉服体验", duration: "30分钟" }
  ];

  // 为每个时间段生成预约详情
  timeSlotsList.value.forEach(slot => {
    // 如果已经有预约详情，则跳过
    if (slot.bookingDetails && slot.bookingDetails.length > 0) return;

    // 创建预约详情数组
    slot.bookingDetails = [];

    // 只为有预约的时间段生成详情
    if (slot.peopleCount > 0) {
      // 根据人数添加预约记录
      for (let i = 0; i < slot.peopleCount; i++) {
        const serviceIndex = Math.floor(Math.random() * serviceTypes.length);
        const service = serviceTypes[serviceIndex];

        const customer = {
          id: `C${10000 + i}`,
          name: `客户${i + 1}`,
          phone: `1381234${i.toString().padStart(4, "0")}`,
          serviceType: service.type,
          serviceDuration: service.duration,
          appointmentTime: formatDate(selectedDate.value) + " " + slot.time,
          // 分配摄影师和化妆师
          photographer:
            i < slot.photographers.length
              ? slot.photographers[i % slot.photographers.length]
              : null,
          makeupArtist:
            i < slot.makeupArtists.length
              ? slot.makeupArtists[i % slot.makeupArtists.length]
              : null
        };

        slot.bookingDetails.push(customer);
      }
    }
  });
};

// 准备Excel导出数据
const prepareExcelData = () => {
  const result = [];

  timeSlotsList.value.forEach(slot => {
    // 格式化摄影师信息
    const photographersStr =
      slot.photographers.map(p => p.name).join(", ") || "无";

    // 格式化化妆师信息
    const makeupArtistsStr =
      slot.makeupArtists.map(m => m.name).join(", ") || "无";

    // 获取预约详情 - 如果没有则使用空数组
    const bookingDetails = slot.bookingDetails || [];

    // 如果没有预约详情或预约人数为0，只添加一条汇总数据
    if (bookingDetails.length === 0) {
      result.push({
        时间段: slot.time,
        预约状态: getStatusText(slot.status),
        预约人数: slot.peopleCount,
        摄影师: photographersStr,
        化妆师: makeupArtistsStr,
        订单信息: "无预约订单"
      });
    } else {
      // 有预约详情时，为每个预约添加一行数据
      bookingDetails.forEach((booking, index) => {
        // 客户信息格式化
        const customerInfo = `${booking.name}(${booking.phone}) - ${booking.serviceType}(${booking.serviceDuration})`;

        // 第一个预约显示时间段信息，后续预约不显示（合并单元格效果）
        result.push({
          时间段: index === 0 ? slot.time : "",
          预约状态: index === 0 ? getStatusText(slot.status) : "",
          预约人数: index === 0 ? slot.peopleCount : "",
          摄影师: index === 0 ? photographersStr : "",
          化妆师: index === 0 ? makeupArtistsStr : "",
          订单信息: customerInfo
        });
      });
    }
  });

  return result;
};

// 初始化
onMounted(() => {
  generateDateList();

  if (process.env.NODE_ENV === "development") {
    // 使用导入的模拟店铺数据
    storeList.value = mockStores;
    selectedStoreId.value = mockStores[0].id;
    updateCurrentStore();

    // 生成初始日期的模拟数据
    generateMockDataForCurrentDate();
  } else {
    // 在生产环境中，调用真实API
    fetchStores();
  }
});
</script>

<style lang="scss" scoped>
.booking-container {
  padding: 24px;
  background-color: var(--el-bg-color-page);

  .booking-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 18px;
        font-weight: bold;
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 10px;

        .store-select {
          width: 200px;
        }

        .settings-btn {
          margin-left: 10px;
        }
      }
    }

    .booking-content {
      padding: 20px 0;

      .store-business-hours {
        margin-bottom: 20px;

        .store-info {
          display: flex;
          justify-content: space-between;
          align-items: center;

          strong {
            margin-left: 5px;
          }

          .el-icon {
            vertical-align: middle;
          }
        }
      }

      .date-selector {
        display: flex;
        justify-content: center;
        margin-bottom: 24px;

        :deep(.el-radio-button__inner) {
          padding: 8px 15px;
        }

        .date-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          .week-day {
            font-size: 14px;
          }

          .date {
            font-size: 16px;
            font-weight: bold;
            margin-top: 4px;
          }
        }

        :deep(.is-today .el-radio-button__inner) {
          background-color: rgba(var(--el-color-primary-rgb), 0.1);
          border-color: var(--el-color-primary);
          color: var(--el-color-primary);
          font-weight: bold;
        }
      }

      .legend {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        gap: 24px;

        .legend-item {
          display: flex;
          align-items: center;
          gap: 6px;

          .color-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;

            &.available {
              background-color: var(--el-color-success);
            }

            &.busy {
              background-color: var(--el-color-warning);
            }

            &.full {
              background-color: var(--el-color-danger);
            }
          }
        }
      }

      .time-slots-grid {
        margin-top: 20px;

        .el-row {
          margin-bottom: 20px;
        }

        .el-col {
          margin-bottom: 16px;
        }

        .time-slot-card {
          height: 100%;
          transition: all 0.3s;

          &.status-available {
            border-left: 4px solid var(--el-color-success);
          }

          &.status-busy {
            border-left: 4px solid var(--el-color-warning);
          }

          &.status-full {
            border-left: 4px solid var(--el-color-danger);
            background-color: rgba(var(--el-color-danger-rgb), 0.05);
          }

          &:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
          }

          .time-slot-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;

            .time {
              font-size: 18px;
              font-weight: bold;
              margin: 0;
            }
          }

          .time-slot-content {
            display: flex;
            flex-direction: column;
            gap: 15px;

            .count-info {
              display: flex;
              justify-content: center;
              margin-bottom: 5px;

              .progress-content {
                display: flex;
                flex-direction: column;
                align-items: center;

                .value {
                  font-size: 20px;
                  font-weight: bold;
                  line-height: 1;
                }

                .label {
                  font-size: 12px;
                  color: var(--el-text-color-secondary);
                }
              }
            }

            .staff-info {
              display: flex;
              flex-direction: column;
              gap: 10px;

              .staff-section {
                .staff-title {
                  font-size: 14px;
                  color: var(--el-text-color-regular);
                  margin-bottom: 5px;
                }

                .staff-list {
                  display: flex;
                  flex-wrap: wrap;
                  gap: 8px;

                  .staff-item {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    min-width: 40px;

                    .staff-avatar {
                      border: 2px solid #fff;
                      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                      margin-bottom: 2px;
                    }

                    .staff-name-tag {
                      font-size: 12px;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      max-width: 100%;
                    }
                  }

                  .no-staff {
                    font-size: 16px;
                    color: var(--el-color-info);
                  }
                }
              }
            }
          }

          .time-slot-footer {
            margin-top: 15px;
            display: flex;
            justify-content: center;
          }
        }
      }
    }
  }
}

.time-slot-detail {
  .detail-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid var(--el-border-color-light);

      .el-icon {
        color: var(--el-color-primary);
      }
    }

    .info-row {
      display: flex;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 80px;
        color: var(--el-text-color-secondary);
      }

      .value {
        color: var(--el-text-color-primary);
      }
    }

    .staff-cards {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;

      .staff-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        border-radius: 8px;
        background-color: var(--el-fill-color-light);
        min-width: 180px;

        .staff-info {
          .staff-name {
            font-weight: 500;
            margin-bottom: 4px;
          }
        }
      }
    }
  }
}

// 媒体查询 - 在中等屏幕上显示3列
@media screen and (max-width: 1400px) {
  .time-slots-grid {
    .el-col {
      width: 33.33% !important;
    }
  }
}

// 媒体查询 - 在小屏幕上显示2列
@media screen and (max-width: 1100px) {
  .time-slots-grid {
    .el-col {
      width: 50% !important;
    }
  }
}

// 媒体查询 - 在移动端显示1列
@media screen and (max-width: 768px) {
  .time-slots-grid {
    .el-col {
      width: 100% !important;
    }
  }

  .booking-container {
    .booking-content {
      .date-selector {
        overflow-x: auto;
        justify-content: flex-start;
        padding-bottom: 10px;
      }
    }
  }
}

// 对话框样式
.settings-dialog {
  .settings-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid var(--el-border-color-light);

      .el-icon {
        color: var(--el-color-primary);
      }
    }

    .settings-form {
      .threshold-hint {
        margin-left: 10px;
        color: var(--el-text-color-secondary);
        font-size: 12px;
      }

      .time-separator {
        margin: 0 10px;
      }
    }
  }
}

.service-duration {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}
</style>
